const moment = require('moment')
const Member = require('../../model/Member')
const User = require('../../model/User')
const PointHistory = require('../../model/PointHistory')
const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')
const request = require('request')
const MemberCard = require('../../model/MemberCard')




module.exports = {

    getUserPoints: async(req, res, next) => {
        try {
            let user = await User.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid }, 'point').exec()
            res.ok('获取成功', member)
        } catch (e) {
            next(e)
        }
    },

    getUserPointHistory: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.order) {
                option.order = req.body.order
            }
            if (req.body.manual) {
                option.manual = req.body.manual
            }
            if (req.body.amount) {
                option.amount = req.body.amount
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            let user = await User.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            option.openid = user.openid
            let count = await PointHistory.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let pointHistory = await PointHistory.find(option).skip((page - 1) * pageSize).limit(pageSize).populate('member order expenseHistory').exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = pointHistory
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    getUserPointHistoryList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if(req.body.userId){
                let user = await User.findOne({_id:req.body.userId,isDelete:0}).exec()
                option.openid = user.openid
            }
            if (req.body.order) {
                option.order = req.body.order
            }
            if (req.body.manual) {
                option.manual = req.body.manual
            }
            if (req.body.amount) {
                option.amount = req.body.amount
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            // let user = await User.findOne({ _id: req.body.id, isDelete: 0 }).exec()
            // option.openid = user.openid
            let count = await PointHistory.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let pointHistory = await PointHistory.find(option).skip((page - 1) * pageSize).limit(pageSize).populate('member order').populate({
                path: 'expenseHistory',
                select: 'store',
                populate: { path: 'store', select: 'name' }
            }).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = pointHistory
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },

    getOneUserPointHistory: async(req, res, next) => {
        try {
            let pointHistory = await PointHistory.findOne({ _id: req.body.id, isDelete: 0 }).populate('member order expenseHistory').exec()
            res.ok('获取成功', pointHistory)
        } catch (e) {
            next(e)
        }
    },

    addUserPointHistory: async(req, res, next) => {
        try {
            let user = await User.findOne({ cellphone: req.body.cellphone, isDelete: 0 }).exec()
            let member = await Member.findOne({ openid: user.openid }, 'point').exec()
            if (req.body.type == 0) {
                member.point = member.point + req.body.amount
            } else if (req.body.type == 1) {
                member.point = member.point - req.body.amount
            }
            await member.save()
            let newPointHistory = new PointHistory({
                openid: user.openid,
                order: req.body.order,
                memo: req.body.memo,
                manual: req.body.manual,
                amount: req.body.amount,
                type: req.body.type,
                isDelete: 0
            })
            await newPointHistory.save()
            res.ok('修改成功', newPointHistory)
        } catch (e) {
            next(e)
        }
    },
    creatMemberCared: async(req, res, next) => {
        try {
            wxPublicAccessToken.getAccessToken(function(access_token) {
                var wxurl = "https://api.weixin.qq.com/card/update?access_token=" + access_token
                let postdata = {
                    // "card": {
                        // "card_type": "MEMBER_CARD",
                        "card_id": "pVBEys-PMXWcQDbflJyERqF-24Ko",
                        "member_card": {
                            "base_info": {
                                "logo_url": "https://beamuse-1301730110.cos.ap-shanghai.myqcloud.com/image/museLogo.png",
                                // "brand_name": "MUSE",
                                "code_type": "CODE_TYPE_QRCODE",
                                "title": "BE A MUSE会员卡",
                                "color": "Color080",
                                "notice": "使用时向服务员出示",
                                "description": "享受会员特权",
                                "date_info": {
                                    "type": "DATE_TYPE_PERMANENT"
                                },
                                // "sku": {
                                //     "quantity": 100000000
                                // },
                                "pay_info": {
                                    "swipe_card": {
                                        "is_swipe_card": true
                                    }
                                },
                                "is_pay_and_qrcode": false,
                                "get_limit":100
                            },
                            "supply_bonus": true,
                            "supply_balance": false,
                            "prerogative": "BE A MUSE会员卡",
                            "auto_activate": true
                        }
                    // }
                }
                request({
                    url: wxurl,
                    method: "POST",
                    timeout: 10000,
                    body: postdata,
                    followRedirect: true,
                    json: true,
                    maxRedirects: 10
                }, function(error, response, body) {
                    console.log(error, body, 'dd')
                    let newMemberCard = new MemberCard({
                        cardId: body.card_id,
                        isDelete: 0
                    })
                    newMemberCard.save(function() {
                        // if (!error) {
                        if (body.errcode == 0) {
                            res.ok('创建会员卡成功')
                        }
                    })
                })
            })
        } catch (e) {
            next(e)
        }
    },

    newMemberGivePointList: async(req, res, next) => {
        try {
            let pointList = await PointHistory.find({amount:100,expenseHistory:null,type:0,expenseDate:{$gte:new Date("2020-08-24")}}).exec()
            let openidList = pointList.map(e => { return String(e.openid) })
            let count = await User.countDocuments({openid:openidList}).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await User.find({ openid:openidList}).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            res.ok('获取成功', result)
        } catch (e) {
            next(e)
        }
    },
};